//
//  MallViewController.m
//  MyNewProject
//
//  Created by sun on 2018/12/3.
//  Copyright © 2018 sun. All rights reserved.
//

#import "MallViewController.h"
#import "YXLProduceListViewController.h"
#import "HGCenterBaseTableView.h"
#import "HGSegmentedPageViewController.h"
#import "HGPageViewController.h"
#import "YXLJifenMallHeadView.h"
#import "MyBillingVC.h"
#import "MyOrderViewController.h"
#import "YPLoginBaseClass.h"

#import "LoginViewController.h"
#import "YCMenuView.h"

#define kPageTabHeight  40
@interface MallViewController ()<UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate, HGSegmentedPageViewControllerDelegate, HGPageViewControllerDelegate>

@property (nonatomic, strong) HGCenterBaseTableView *tableView;
@property (nonatomic, strong) UIImageView *headerImageView;
@property (nonatomic, strong) UIImageView *avatarImageView;
@property (nonatomic, strong) UILabel *nickNameLabel;
@property (nonatomic, strong) HGSegmentedPageViewController *segmentedPageViewController;
@property (nonatomic) BOOL cannotScroll;
@property (nonatomic, strong)UIView *topCoverView;
@property (nonatomic, strong) NSMutableArray *shaiXuanArr;

@end

static CGFloat const HeaderImageViewHeight = 150;

@implementation MallViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (@available(iOS 11.0, *)) {
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.gk_navTitle = @"积分商城";
    //如果使用自定义的按钮去替换系统默认返回按钮，会出现滑动返回手势失效的情况
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    SKAdd_Observer(@"munuDeal", self,munuDeal:, nil);
    SKAdd_Observer(@"SelectItemAtIndexPath", self,selectItemAtIndexPath:, nil);


    [self setupSubViews];
    [self getShaiXuanData:0];

}
-(void)munuDeal:(NSNotification *)notification
{
    if (self.shaiXuanArr.count ==0) {
        return;
    }
    NSDictionary * infoDic = [notification object];
    UIButton * myBtn = infoDic[@"MYSignImage"];


    NSArray *titles = @[@"品质生活", @"限时兑换", @"猜你喜欢"];

    NSMutableArray * arrayAction = [NSMutableArray array];
    for (int i = 0; i<self.shaiXuanArr.count; i++) {

        NSDictionary *dic = self.shaiXuanArr[i];
        YCMenuAction *action1 = [YCMenuAction actionWithTitle:[NSString stringWithFormat:@"%@",[dic stringWithFilted:@"title"] ] image:nil handler:^(YCMenuAction *action, int selectIndex)  {
            NSLog(@"点击了%@ -----%d-",action.title,selectIndex);
            NSDictionary *dic = self.shaiXuanArr[selectIndex];

            [SKNotificationCenter postNotificationName:titles[self.segmentedPageViewController.selectedIndex] object:@{
                                                                                @"ItemAtIndexPath":@([[dic stringWithFilted:@"id"] intValue])
                                                                                         }];
        }];
        [arrayAction addObject:action1];
    }
    // Do any additional setup after loading the view.





    YCMenuView *view = [YCMenuView menuWithActions:arrayAction width:140 relyonView:myBtn];
    [view show];


}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [self obtainUserInfo];

    [self updateNavigationBarBackgroundColor];
}
-(void)obtainUserInfo
{

    if (IsStrEmpty([UserInfoSingleton shareInstance].userInfo.loginKey)) {
        YXLJifenMallHeadView *headView = [_headerImageView viewWithTag:123456789];
        if (headView) {

            headView.jifenNumLab.text = @"0";
        }

        return;
    }
    SKWeakSelf;

    [YQNetworking postWithUrl:@"my/getUserInfo" params:@{@"uid":self.uid,@"loginKey":self.loginKey} reloginRefreshBlock:^(id response) {

        NSLog(@"-------------");
    } successBlock:^(id response) {
        YPLoginBaseClass * baseLogin = [YPLoginBaseClass modelObjectWithDictionary:response];
        if ([baseLogin.status isEqualToString:@"ok"]) {
            NSDictionary * dic = (NSDictionary *)response;
            SKUserUserDefaults_Save(dic[@"user_info"] , @"UserInfo");
            [UserInfoSingleton shareInstance].userInfo = baseLogin.userInfo;
            YXLJifenMallHeadView *headView = [weakSelf.headerImageView viewWithTag:123456789];
            if (headView) {
                if (!IsStrEmpty([UserInfoSingleton shareInstance].userInfo.jifen)) {
                    headView.jifenNumLab.text = [NSString stringWithFormat:@"%@",[UserInfoSingleton shareInstance].userInfo.jifen];
                }
            }
        }
    } failBlock:^(NSError *error) {

    }];
}
#pragma mark - Private Methods
- (void)setupSubViews {
    //[self.view insertSubview:self.tableView belowSubview:self.gk_navigationBar];
    [self.view addSubview:self.tableView];
    [self.tableView addSubview:self.headerImageView];
    [self.headerImageView addSubview:self.topCoverView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        //make.edges.equalTo(self.view);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.top.mas_equalTo(SKTopBar_Height);
    }];
    [self.avatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.headerImageView);
        make.size.mas_equalTo(CGSizeMake(80, 80));
        make.bottom.mas_equalTo(-70);
    }];
    [self.nickNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.headerImageView);
        make.width.mas_lessThanOrEqualTo(200);
        make.bottom.mas_equalTo(-40);
    }];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        NSDictionary *paramDic = @{@"tableView":self.tableView};
        [[NSNotificationCenter defaultCenter] postNotificationName:@"mallPageHeadRefresh" object:paramDic];
    }];

}

- (void)updateNavigationBarBackgroundColor {
    CGFloat alpha = 0;
    CGFloat currentOffsetY = self.tableView.contentOffset.y;
    if (-currentOffsetY <= SKNavBar_Height) {
        alpha = 1;
    } else if ((-currentOffsetY > SKNavBar_Height) && -currentOffsetY < HeaderImageViewHeight) {
        alpha = (HeaderImageViewHeight + currentOffsetY) / (HeaderImageViewHeight - SKNavBar_Height);
    } else {
        alpha = 0;
    }
    self.topCoverView.backgroundColor = SKRGBAColor(255, 255, 255, alpha);
    
    
}

#pragma mark - UIScrollViewDelegate
- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView {
    [self.segmentedPageViewController.currentPageViewController makePageViewControllerScrollToTop];
    return YES;
}

/**
 * 处理联动
 * 因为要实现下拉头部放大的问题，tableView设置了contentInset，所以试图刚加载的时候会调用一遍这个方法，所以要做一些特殊处理，
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //第一部分：处理导航栏
    [self updateNavigationBarBackgroundColor];
    
    //第二部分：处理手势冲突
    CGFloat contentOffsetY = scrollView.contentOffset.y;
    //吸顶临界点(此时的临界点不是视觉感官上导航栏的底部，而是当前屏幕的顶部相对scrollViewContentView的位置)
    CGFloat criticalPointOffsetY = [self.tableView rectForSection:0].origin.y;
    
    //利用contentOffset处理内外层scrollView的滑动冲突问题
    if (contentOffsetY >= criticalPointOffsetY) {
        /*
         * 到达临界点：
         * 1.未吸顶状态 -> 吸顶状态
         * 2.维持吸顶状态(pageViewController.scrollView.contentOffsetY > 0)
         */
        //“进入吸顶状态”以及“维持吸顶状态”
        self.cannotScroll = YES;
        scrollView.contentOffset = CGPointMake(0, criticalPointOffsetY);
        [self.segmentedPageViewController.currentPageViewController makePageViewControllerScroll:YES];
    } else {
        /*
         * 未达到临界点：
         * 1.吸顶状态 -> 不吸顶状态
         * 2.维持吸顶状态(pageViewController.scrollView.contentOffsetY > 0)
         */
        if (self.cannotScroll) {
            //“维持吸顶状态”
            scrollView.contentOffset = CGPointMake(0, criticalPointOffsetY);
        } else {
            /* 吸顶状态 -> 不吸顶状态
             * pageViewController.scrollView.contentOffsetY <= 0时，会通过代理HGPageViewControllerDelegate来改变当前控制器self.cannotScroll的值；
             */
        }
    }
    
    //第三部分：
    /**
     * 处理头部自定义背景视图 (如: 下拉放大)
     * 图片会被拉伸多出状态栏的高度
//     */
//    if(contentOffsetY <= -HeaderImageViewHeight) {
//        if (self.isEnlarge) {
//            CGRect f = self.headerImageView.frame;
//            //改变HeadImageView的frame
//            //上下放大
//            f.origin.y = contentOffsetY;
//            f.size.height = -contentOffsetY;
//            //左右放大
//            f.origin.x = (contentOffsetY * SCREEN_WIDTH / HeaderImageViewHeight + SCREEN_WIDTH) / 2;
//            f.size.width = -contentOffsetY * SCREEN_WIDTH / HeaderImageViewHeight;
//            //改变头部视图的frame
//            self.headerImageView.frame = f;
//        }else{
//            scrollView.bounces = NO;
//        }
//    }else {
//        scrollView.bounces = YES;
//    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [self addChildViewController:self.segmentedPageViewController];
    [cell.contentView addSubview:self.segmentedPageViewController.view];
    [self.segmentedPageViewController didMoveToParentViewController:self];
    [self.segmentedPageViewController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(cell.contentView);
    }];
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return SCREENH_HEIGHT - SKNavBar_Height;
}

//解决tableView在group类型下tableView头部和底部多余空白的问题
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

#pragma mark - HGSegmentedPageViewControllerDelegate
- (void)segmentedPageViewControllerWillBeginDragging {
    self.tableView.scrollEnabled = NO;
}

- (void)segmentedPageViewControllerDidEndDragging {
    self.tableView.scrollEnabled = YES;
}
-(void)segmentedPageViewControllerDidEndDeceleratingWithPageIndex:(NSInteger)index
{

    [self getShaiXuanData:index];


}


-(void)selectItemAtIndexPath:(NSNotification *)notification
{
    NSDictionary * infoDic = [notification object];
    int index = [infoDic[@"ItemAtIndexPath"] intValue];

    [self getShaiXuanData:index];
}

-(void)getShaiXuanData:(int)index
{
    SKWeakSelf;
    int type = 1;
    switch (index) {
        case 0:
        {
            type = 1;
        }
            break;
        case 1:
        {
            type = 2;
        }
            break;
        case 2:
        {
            type = 4;
        }
            break;

        default:
            break;
    }

    [YQNetworking postWithUrl:@"Jifen/getJifenClass" params:@{@"type":@(type),@"page":@(0)} reloginRefreshBlock:^(id response) {

    } successBlock:^(id response) {

        NSLog(@"------%@-------",response);

        if ([response[@"status"] isEqualToString:@"ok"]) {

            self.shaiXuanArr = response[@"data"];
        }
        else
        {
            self.shaiXuanArr = [NSMutableArray array];
        }

    } failBlock:^(NSError *error) {

    }];

}
-(NSMutableArray*)shaiXuanArr
{
    if (_shaiXuanArr == nil) {
        _shaiXuanArr = [NSMutableArray array];
    }
    return _shaiXuanArr;
}
#pragma mark - HGPageViewControllerDelegate
- (void)pageViewControllerLeaveTop {
    self.cannotScroll = NO;
}

#pragma mark - Lazy
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[HGCenterBaseTableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.contentInset = UIEdgeInsetsMake(HeaderImageViewHeight, 0, 0, 0);
        _tableView.bounces =NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

- (UIImageView *)headerImageView {
    if (!_headerImageView) {
        _headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -HeaderImageViewHeight, SCREEN_WIDTH, HeaderImageViewHeight)];
        _headerImageView.userInteractionEnabled = YES;
        YXLJifenMallHeadView *headView = [[YXLJifenMallHeadView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 150)];
        //notifyView.clipsToBounds = YES;

        headView.tag = 123456789;
        [headView.jifenDetailBtn addTarget:self action:@selector(jifenDetailBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [headView.jifenHistoryBtn addTarget:self action:@selector(jifenHistoryBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_headerImageView addSubview:headView];
        
    }
    return _headerImageView;
}

-(UIView *)topCoverView
{
    if (!_topCoverView) {
        _topCoverView = [[UIView alloc] initWithFrame:CGRectMake(0, HeaderImageViewHeight - 50, SCREEN_WIDTH, 50)];
        _topCoverView.backgroundColor = [UIColor whiteColor];
    }
    
    return _topCoverView;
}

- (HGSegmentedPageViewController *)segmentedPageViewController {
    if (!_segmentedPageViewController) {
//        NSArray *titles = @[@"品质生活", @"床上优选", @"限时兑换", @"猜你喜欢"];
//        NSArray *dataTypeArry = @[@(MallLifeProductType), @(MallBedProductType), @(MallLimitProductType),@ (MallLikeProductType)];
        NSArray *titles = @[@"品质生活", @"限时兑换", @"猜你喜欢"];
        NSArray *dataTypeArry = @[@(MallLifeProductType), @(MallLimitProductType),@ (MallLikeProductType)];
        NSMutableArray *controllers = [NSMutableArray array];
        for (int i = 0; i < titles.count; i++) {
            YXLProduceListViewController *controller = [[YXLProduceListViewController alloc] init];
            controller.dataType = [dataTypeArry[i] integerValue];
            controller.topHeight = SKNavBar_Height;
            controller.delegate = self;
            [[NSNotificationCenter defaultCenter] addObserver:controller selector:@selector(shuaXinData:) name:titles[i] object:nil];
            [controllers addObject:controller];
        }
        _segmentedPageViewController = [[HGSegmentedPageViewController alloc] init];
        _segmentedPageViewController.isShow = 1;

        _segmentedPageViewController.pageViewControllers = controllers.copy;
        _segmentedPageViewController.categoryView.titles = titles;
        _segmentedPageViewController.categoryView.originalIndex = self.selectedIndex;
        _segmentedPageViewController.delegate = self;
    }
    return _segmentedPageViewController;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)jifenDetailBtnClick
{
  
    
    if (SKUserUserDefaults_Get(@"UserInfo")) {
        MyBillingVC * accD = [[MyBillingVC alloc]init];
        accD.selectedIndex = 1;
        
        [self.navigationController pushViewController:accD animated:YES];
        NSLog(@"jifenDetailBtnClick");
    }
    else
    {
        LoginViewController * loginVC =[[LoginViewController alloc] init];
        loginVC.myLoginResult = ^(id model) {
            
        };
        
        
        [self.navigationController pushViewController:loginVC animated:YES];
    }
    
}

-(void)jifenHistoryBtnClick
{
    
    if (SKUserUserDefaults_Get(@"UserInfo")) {
        MyOrderViewController * accD = [[MyOrderViewController alloc]init];
        accD.selectedCondition = 0;
        [self.navigationController pushViewController:accD animated:YES];
        NSLog(@"jifenDetailBtnClick");
        
    }
    else
    {
        LoginViewController * loginVC =[[LoginViewController alloc] init];
        loginVC.myLoginResult = ^(id model) {
            
        };
        
        
        [self.navigationController pushViewController:loginVC animated:YES];
    }
}

@end
